//
//  RegisterPacketCenter.m
//  HiQServer
//
//  Created by arvintan on 12-8-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RegisterPacketCenter.h"
#import "EncryptorWithKey.h"
#import "SockPacket.h"
#import "MacroComd.h"
#import "MiniSocket.h"
#import "MainSocketDelegate.h"
#import "MysqlDB.h"

NSString *REGISTER_KEY =@"register";
#define SEX_LEN 3

@implementation RegisterPacketCenter

-(NSData*) dataCmd:(NSData *)data cmd:(NSUInteger)cmdFlag subcmd:(NSUInteger)subCmdFlag
{
    NSUInteger length = data.length + 16;
    NSLog(@"data length is %lu,%lu",data.length,sizeof(NSUInteger));
    NSMutableData *dataWithCmd = [NSMutableData dataWithBytes:&(length) length:sizeof(NSUInteger)];
    [dataWithCmd appendBytes:&(cmdFlag) length:sizeof(NSUInteger)];
    [dataWithCmd appendBytes:&(subCmdFlag) length:sizeof(NSUInteger)];
    [dataWithCmd appendData:data];
    
    return dataWithCmd;
}


-(void)MessageDispatch: (SockPacket *)packet
{
    void *byte = (void*)[packet.packetContent bytes];
    NSUInteger subFun = *((NSUInteger*)(byte + sizeof(NSUInteger)));
    
    // 初始化数据库并连接
    MysqlDB *mysql = [[MysqlDB alloc] init];
    [mysql connectHost:hostIp connectUser:userName connectPassword:password connectName:dbName];
    
    switch (subFun) {
        case CMD_REG_REQUEST:
        {   
            NSData *encryptData = [[NSData alloc] initWithBytes:(byte + 16) length:(packet.packetLen - 16)];
            NSData *decryptData = [EncryptorWithKey decryptWIthKey:encryptData forKey:REGISTER_KEY];
            void *bytes = (void*)[decryptData bytes];
            //获取ID，密码长度以及密码
            NSUInteger nameLen = *((NSUInteger*)(bytes));
            NSUInteger pwdLen = *((NSUInteger*)(bytes + sizeof(NSUInteger)));
            NSUInteger imageLen = *((NSUInteger*)(bytes + 2*sizeof(NSUInteger)));
            NSString *name = [[NSString alloc] initWithBytes:(bytes + 3*sizeof(NSUInteger)) length:nameLen encoding:NSUTF8StringEncoding];
            NSString *pwd = [[NSString alloc] initWithBytes:(bytes + 3*sizeof(NSUInteger) + nameLen) length:pwdLen encoding:NSUTF8StringEncoding];
            NSString *image = [[NSString alloc] initWithBytes:(bytes + 3*sizeof(NSUInteger) + nameLen + pwdLen) length:imageLen encoding:NSUTF8StringEncoding];
            //NSString *sex = [[NSString alloc] initWithBytes:(bytes + 3*sizeof(NSUInteger) + nameLen + pwdLen + imageLen) length:SEX_LEN encoding:NSUTF8StringEncoding];           
            
            
            NSString *escapeName = [mysql doEscapeString:name];
            NSString *escapePwd = [mysql doEscapeString:pwd];
            //数据库操作
            NSString *sqlQuery = [NSString stringWithFormat:@"select max(userID) from tbUser"];
            NSMutableArray *dataResult = [mysql doDataQuery:sqlQuery];
            for (int i = 0 ; i < [dataResult count]; ++i) {
                NSLog(@"%@",[dataResult objectAtIndex:i]);
            }
            //用来传输的数据
            NSData *dataWithCmd;
            if([dataResult count])
            {
                NSArray *temp = [dataResult objectAtIndex:0];
                NSString *maxUserID = [temp objectAtIndex:0];
                NSUInteger userID = [maxUserID integerValue] + 1;
                if ([maxUserID integerValue] == 0) {
                    userID = 10000;
                }
                //NSUInteger maxUserID = [dataResult objectAtIndex:0];
                NSString *sqlInsert = [NSString stringWithFormat:@"insert into tbUser(userID,userName,password,UserImage) values('%ld','%@','%@','%@')",userID,escapeName,escapePwd,image];
                NSLog(@"test %@",sqlInsert);
                [mysql doDataInsert:sqlInsert];
                NSLog(@"Register success ---- userID %ld",userID);
                NSData *data = [[NSData alloc] initWithBytes:&(userID) length:sizeof(NSUInteger)];
                dataWithCmd = [self dataCmd:data cmd:CMD_FUN_REGISTER subcmd:CMD_REG_RET_YES];
            }
            else 
            {
                NSLog(@"Register fail");
                NSUInteger errorID = 0;
                NSData *data = [[NSData alloc] initWithBytes:&(errorID) length:sizeof(NSUInteger)];
                dataWithCmd = [self dataCmd:data cmd:CMD_FUN_REGISTER subcmd:CMD_REG_RET_NO];
            } 
            [packet.subAsynSocket writeData:dataWithCmd withTimeout:-1 tag:0];  
        }
        break;            
        default:
            NSLog(@"unknow register request");
            break;
    }
    //结束与数据库连接
    [mysql disconnect];
}

@end
